package org.hxzon.util;

import java.util.Calendar;
import java.util.Date;

public class DateUtil {
    public static Calendar toCalendar(Date orig) {
        Calendar c = Calendar.getInstance();
        c.setLenient(false);
        c.setTime(orig);
        return c;
    }

    //month is 1-12
    public static Date setDate(Date orig, int year, int month, int date) {
        return setDateTime(orig, year, month, date, -1, -1, -1);
    }

    public static Date setTime(Date orig, int hourOfDay, int minute, int second) {
        return setDateTime(orig, -1, -1, -1, hourOfDay, minute, second);
    }

    public static Date setDateTime(Date orig, int year, int month, int date, int hourOfDay, int minute, int second) {
        if (orig == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        // getInstance() returns a new object, so this method is thread safe.
        Calendar c = toCalendar(orig);
        if (year > 0) {
            c.set(Calendar.YEAR, year);
        }
        if (month > 0) {
            c.set(Calendar.MONTH, month - 1);
        }
        if (date > 0) {
            c.set(Calendar.DATE, date);
        }
        if (hourOfDay > -1) {
            c.set(Calendar.HOUR_OF_DAY, hourOfDay);
        }
        if (minute > -1) {
            c.set(Calendar.MINUTE, minute);
        }
        if (second > -1) {
            c.set(Calendar.SECOND, second);
        }
        return c.getTime();
    }

    public static int getYear(Calendar calendar) {
        return calendar.get(Calendar.YEAR);
    }

    public static int getMonth(Calendar calendar) {
        return calendar.get(Calendar.MONTH) + 1;
    }

    public static int getDate(Calendar calendar) {
        return calendar.get(Calendar.DATE);
    }
}
